﻿using LeSoft.Application.Bussiness;
using LeSoft.Application.Cache;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Collections;
using System.Web.Mvc;
using Newtonsoft.Json;

namespace LeSoft.Application.Web.Areas.ResourceManage.Controllers
{
    public class RS_WarehouseController : MvcControllerBase
    {
        //
        // GET: /ResourceManage/RS_Warehouse/

        private WarehouseBLL bll = new WarehouseBLL();

        #region 视图
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Form()
        {
            return View();
        }


        #endregion

        #region 获取数据
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取仓库集合", "GetWarehouseInfoList")]
        public ActionResult GetWarehouseInfoList()
        {
            var data = bll.GetWarehouseInfoList().ToList();
            return Content(data.ToJson());
        }

        /// <summary>
        /// 获取仓库树列表
        /// </summary>
        /// <param name="queryJson"></param>
        /// <returns></returns> 
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取仓库树列表", "GetTreeListJson")]
        public ActionResult GetTreeListJson(string queryJson)
        {
            var queryParam = queryJson.ToJObject();
            var data = bll.GetWarehouseInfoList().ToList();
            var query = new OrganizeCache().GetList().ToList();
            if (!queryParam["condition"].IsEmpty() && !queryParam["keyword"].IsEmpty())
            {

                var condition = queryParam["condition"].ToString();
                var keyword = queryParam["keyword"].ToString();
                switch (condition)
                {
                    case "Name":
                        data = data.Where(t => t.Name.Contains(keyword)).ToList();
                        break;
                    case "Code":
                        data = data.Where(t => t.Code.Contains(keyword)).ToList();
                        break;
                    case "PSMemo":
                        data = data.Where(t => t.PSMemo.Contains(keyword)).ToList();
                        break;
                    default:
                        break;
                }

                data = data.Where(t => t.Code.Contains(queryParam["keyword"].ToString())).ToList();

            }

            var TreeList = new List<TreeGridEntity>();
            foreach (WarehouseInfoEntity item in data)
            {
                TreeGridEntity tree = new TreeGridEntity();
                bool hasChildren = data.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                tree.id = item.Id;
                var parentId = item.ParentId.IsEmpty() ? "0" : item.ParentId;
                tree.parentId = parentId;
                tree.expanded = true;
                tree.hasChildren = hasChildren;
                if (item.ParentId != null)
                {
                    item.PStructId = item.PStructId.IsEmpty() ? "" : new PStructBLL().GetEntity(item.PStructId).AllName;
                }
                else
                {
                    item.ParentId = "---";
                }
                if (item.OrganizeId != null)
                {
                    var OName = query.Where(e => e.OrganizeId == item.OrganizeId).FirstOrDefault();
                    item.OrganizeId = OName.IsEmpty() ? "---" : OName.FullName;
                }
                else
                {
                    item.OrganizeId = "---";
                }
                tree.entityJson = item.ToJson();
                TreeList.Add(tree);
            }
            return Content(TreeList.TreeJson());
            //return Content(data.ToJson());
        }
        /// <summary>
        /// 获取仓库实体
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns> 
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取仓库实体", "GetFormJson")]
        public ActionResult GetFormJson(string keyValue)
        {
            var data = bll.GetWarehouseInfoEntity(keyValue);
            return Content(data.ToJson());
        }

        /// <summary>
        /// 获取仓库树--带All
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取仓库树（All）", "GetTreeJson")]
        public ActionResult GetTreeJson()
        {
            var data = bll.GetWarehouseInfoList().ToList();
            var treeList = new List<TreeEntity>();
            TreeEntity tree1 = new TreeEntity { id = "All", text = "所有仓库", value = "All", parentId = "0", isexpand = true, complete = true, hasChildren = true };
            treeList.Add(tree1);
            foreach (WarehouseInfoEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.ParentId == item.ParentId) == 0 ? false : true;
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Id;
                tree.parentId = item.ParentId == "0" ? "All" : item.ParentId;
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                treeList.Add(tree);
            }

            return Content(treeList.TreeToJson());
        }
        /// <summary>
        /// 获取仓库树
        /// </summary>
        /// <returns></returns> 
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取仓库树", "GetWarehouseInfoTree")]
        public ActionResult GetWarehouseInfoTree(string queryJson)
        {
            var data = bll.GetWarehouseInfoList().ToList();
            if (!string.IsNullOrEmpty(queryJson))
            {
                var queryParam = queryJson.ToJObject();
                if (!queryParam["OrganizeId"].IsEmpty())
                {
                    string OrganizeId = new OrganizeCache().GetSonOrganizeId(queryParam["OrganizeId"].ToString());
                    data = data.Where(t => OrganizeId.Contains(t.OrganizeId)).ToList();
                }
            }
            var treeList = new List<TreeEntity>();
            foreach (WarehouseInfoEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.ParentId == item.ParentId) == 0 ? false : true;
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Id;
                tree.parentId = item.ParentId == "0" ? "0" : item.ParentId;
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.Attribute = "OrganizeId";
                tree.AttributeValue = item.OrganizeId;
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }
        /// <summary>
        /// 获取仓库树--根据机构
        /// </summary>
        /// <param name="OrganizeId"></param>
        /// <returns></returns> 
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取仓库树(组织机构)", "GetWarehouseTreeByOrganizedId")]
        public ActionResult GetWarehouseTreeByOrganizedId(string OrganizeId)
        {
            var data = bll.GetWarehouseInfoList().ToList();
            OrganizeId = new OrganizeCache().GetSonOrganizeId(OrganizeId);
            data = data.Where(e => OrganizeId.Contains(e.OrganizeId)).ToList();
            var treeList = new List<TreeEntity>();
            foreach (WarehouseInfoEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.ParentId == item.ParentId) == 0 ? false : true;
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Id;
                tree.parentId = item.ParentId == "0" ? "0" : item.ParentId;
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                treeList.Add(tree);
            }

            return Content(treeList.TreeToJson());
        }

        #endregion

        #region 保存数据
        /// <summary>
        /// 保存仓库资料
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "保存仓库资料", "SaveForm")]
        public ActionResult SaveForm(string keyValue, WarehouseInfoEntity entity)
        {
            var type = entity.ParentId;
            if (type == "All")
            {
                return Error("所有仓库不能作为上级仓库使用！");
            }
            if (entity.IsDefault == 1)
            {
                if (((bll.GetWarehouseInfoList()).Where(e => e.IsDefault == 1)).Count() >= 1)
                {
                    return Error("系统只能有一个默认仓库！");
                }
                else
                {
                    try
                    {
                        bll.SaveForm(keyValue, entity);
                        return Success("操作成功。");
                    }
                    catch (Exception e)
                    {
                        return Error(e.Message);
                    }
                }

            }
            else
            {
                try
                {
                    bll.SaveForm(keyValue, entity);
                    return Success("操作成功。");
                }
                catch (Exception e)
                {
                    return Error(e.Message);
                }
            }

        }
        /// <summary>
        /// 删除仓库实体
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns> 
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "删除仓库实体", "RemoveForm")]
        public ActionResult RemoveForm(string keyValue)
        {

            var data = bll.GetWarehouseInfoList().Where(e => e.ParentId == keyValue).ToList();
            if (data.Count() == 0)
            {
                try
                {
                    bll.RemoveForm(keyValue);
                    return Success("删除成功。");
                }
                catch (Exception e)
                {
                    return Error(e.Message);
                }
            }
            else
            {
                return Error("请先删除其子节点！");
            }


        }
        #endregion

        #region 数据验证

        //数据验证
        public ActionResult ChkType(string key, string Type)
        {

            var Msg = "";
            switch (key)
            {
                case "Product":
                    if (Type == "All")
                    {
                        Msg = "所有物品不能作为物品类型使用！";
                    }
                    else
                    {
                        var data = bll.GetProductTypeList().Where(e => e.ParentId == Type).ToList();
                        if (data.Count != 0)
                        {
                            Msg = "只有最末级别类型，才能添加物品！";
                        }
                    }
                    break;

                case "Warehouse":
                    if (Type == "All")
                    {
                        Msg = "所有仓库不能作为仓库使用！";
                    }
                    break;
                case "ProductType":
                    if (Type == "All")
                    {
                        Msg = "所有物品不能作为物品类型使用！";
                    }
                    var query = bll.GetProductInfoList().Where(e => e.Type == Type).ToList();
                    if (query.Count() != 0)
                    {
                        Msg = "该父类挂有物品，不能作为上级父类！";
                    }
                    break;
                default:
                    break;
            }
            return Content(Msg);

        }

        #endregion








    }

}
